package com.uduemc.biso.node.web.api.home.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.web.api.exception.NotFoundException;
import com.uduemc.biso.node.web.api.service.RepertoryService;

@Controller()
@RequestMapping("/api/home/repertory")
public class HRepertoryController {

	@Autowired
	private RepertoryService repertoryServiceImpl;

	@GetMapping(value = { "/images/{id:\\d+}/{filename}.{suffix}" })
	@ResponseBody
	public void image(@PathVariable("id") long id, @PathVariable("filename") String filename,
			@PathVariable("suffix") String suffix, HttpServletResponse response)
			throws NotFoundException, JsonParseException, JsonMappingException, JsonProcessingException, IOException {

		if (id < 1 || StringUtils.isEmpty(filename) || StringUtils.isEmpty(suffix)) {
			throw new NotFoundException("请求参数异常！");
		}

		HRepertory hRepertory = repertoryServiceImpl.getInfoByid(id);

		if (!hRepertory.getUnidname().equals(filename) || !hRepertory.getSuffix().equals(suffix)) {
			throw new NotFoundException("未能找到资源文件数据！");
		}

		imageResponse(response, hRepertory.getFilepath(), hRepertory.getSuffix());

		return;
	}

	protected void imageResponse(HttpServletResponse response, String imagePath, String suffix)
			throws NotFoundException {
		FileInputStream openInputStream = null;
		File file = null;
		try {
			file = new File(imagePath);
			openInputStream = FileUtils.openInputStream(file);

			if (openInputStream == null) {
				throw new NotFoundException("读取 repertory 文件失败！ imagePath: " + imagePath);
			}

			long size = file.length();
			byte[] temp = new byte[(int) size];
			openInputStream.read(temp, 0, (int) size);
			openInputStream.close();
			byte[] data = temp;
			OutputStream out = response.getOutputStream();
			response.setContentType("image/" + suffix);
			out.write(data);

			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
			throw new NotFoundException("读取 repertory 文件失败！ imagePath: " + imagePath);
		} finally {
			if (openInputStream != null) {
				try {
					openInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
